package controllers

import (
	"encoding/json"
	"errors"

	"gitee.com/lzqysoft/ims/libs/encrypt"
	// "strconv"
	"strings"
	"time"
	"gitee.com/lzqysoft/ims/models"

	"github.com/astaxie/beego"
)

// OrderController operations for Order
type OrderController struct {
	 CommonController
}

// URLMapping ...
func (c *OrderController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("OrderApply", c.OrderApply)
	c.Mapping("GetMyOrder",c.GetMyOrder)
}

// Ord 订单前端json数据
type Ord struct {
	Id            string          `json:"Id"`
	Cname         string          `json:"Cname"`
	CustId        string          `json:"CustId"`
	CustName 	string 				`json:CustName`
	DiscountPrice float64         `json:"DiscountPrice"`
	Name          string          `json:"Name"`
	Off           float64         `json:"Off"`
	Price         float64         `json:"Price"`
	Remark        string          `json:"Remark"`
	Sales         []*models.Sales `json:"Sales"`
	Receiv        []*models.Recive    	`json:"Receiv"`
}


// Post ...
// @Title Post
// @Description create Order
// @Param	body		body 	models.Order	true		"body for Order content"
// @Success 201 {int} models.Order
// @Failure 403 body is empty
// @router / [post]
func (c *OrderController) Post() {
	var v models.Order
	var p Ord
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrNoData)
	}
	err = json.Unmarshal(rdata, &p)
	v.Name = p.Name
	v.CustId = p.CustId
	v.UserId = user.Id
	v.Price = p.Price
	v.DiscountPrice = p.DiscountPrice
	v.Off = p.Off
	v.Remark = p.Remark
	v.Isdelete = 0
	v.Status = 1
	v.Creater = user.Abbr
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.CustName = p.CustName
	v.Id = encrypt.GetGuid()
	_, err = models.AddOrder(&v)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrDatabase)
	}
	for _, s := range p.Sales {
		s.Id = encrypt.GetGuid()
		s.OrderId = v.Id
		s.Creater = user.Abbr
		s.Ctime = v.Ctime
		s.Updater = v.Updater
		s.Utime = v.Utime
		_, err = models.AddSales(s)
	}
	beego.Debug(p.Receiv)
	err = models.AddReceivByRecive(p.Receiv,v.Id,c.User.Abbr)
	if err != nil {
		//c.RetSuccess("收款单添加失败")
		beego.Debug(err)
	}
	beego.Debug("添加了收款单，单未启用！")
	c.Dlog("添加了销售订单", v.Id)
	c.RetSuccess(v.Id)
}

// GetOne ...
// @Title Get One
// @Description get Order by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Order
// @Failure 403 :id is empty
// @router /:id [get]
func (c *OrderController) GetOne() {
	id := c.Ctx.Input.Param(":id")
	beego.Debug("GetMyOrder 调用了这里？")
	v, err := models.GetOrderById(id)
	if err != nil {
		//c.Data["json"] = err.Error()
		beego.Debug(err)
		c.RetSuccess(err.Error())
	} else {
		//c.Data["json"] = v
		c.RetSuccess(v)
	}
	//c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get Order
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Order
// @Failure 403
// @router / [get]
func (c *OrderController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	query["Isdelete"] = "0"
	query["Status"] = "1"
	limit = -1
	l, err := models.GetAllOrder(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError( ErrDatabase)
	}

	c.RetSuccess(l)
}

// Put ...
// @Title Put
// @Description update the Order
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Order	true		"body for Order content"
// @Success 200 {object} models.Order
// @Failure 403 :id is not int
// @router /Update [post]
func (c *OrderController) Update() {
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrToken)
	}
	// var v models.Preorder
	var p Ord
	err = json.Unmarshal(rdata, &p)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrInputData)
	}
	v, _ := models.GetOrderById(p.Id)
	models.DeleteSalesByOrder(p.Id)

	v.Name = p.Name
	v.CustId = p.CustId
	v.UserId = user.Id
	v.Price = p.Price
	v.DiscountPrice = p.DiscountPrice
	v.Off = p.Off
	v.Remark = p.Remark
	v.Updater = user.Abbr
	v.Utime = time.Now()
	v.Id = p.Id
	err = models.UpdateOrderById(v)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrDatabase)
	}
	for _, s := range p.Sales {
		s.Id = encrypt.GetGuid()
		s.OrderId = v.Id
		s.Creater = user.Abbr
		s.Ctime = v.Ctime
		s.Updater = v.Updater
		s.Utime = v.Utime
		_, err = models.AddSales(s)
	}
	c.Dlog("修改了销售订单,id为：", v.Id)
	c.RetSuccess(v.Id)
}

// Delete ...
// @Title Delete
// @Description delete the Order
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *OrderController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError( ErrInputData)
	}

	err = models.SoftDeleteOrder(id, user.Name)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrDatabase)
	}
	c.Dlog("删除了销售订单", id)
	c.RetSuccess(id)
}

// DeleteOrderList 删除销售订单列表
// @Title DeleteUsers
// @Description DeleteUsers
// @Success 200
// @Failure 403 :
// @router /DeleteOrderList [post]
func (c *OrderController) DeleteOrderList() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		//		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteOrder(id, user.Name)
		if err != nil {
			c.RetError( ErrDatabase)
		}
		c.Dlog("删除了订单", id)
	}
	c.RetSuccess("ok")
}

// OrderApply ...
// @Title OrderApply
// @Description 申请上报
// @Param	body		body 	models.Order	true		"body for Assetsbuy content"
// @Success 201 {int} models.Order
// @Failure 403 body is empty
// @router /OrderApply [post]
func (c *OrderController) OrderApply() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		busyid := value.(string)
		flow, err :=   models.GetFlowByName("销售订单")
		fins, err :=   models.InitFSM(user, flow.Id, "yjk_order", busyid)
		beego.Debug("fins err: ", fins)
		fsm :=   models.GetFSM(fins)
		// // beego.Debug("fsm err: ", fsm)
		ev, _ :=   models.GetEventByName("上报")
		err = fsm.Trigger(fins.Currentstate, ev.Id, fins)
		if err != nil {
			beego.Error("trigger1 err: ", err)
		}
		c.Dlog("上报了销售订单", busyid)
	}

	// ts, err := models.GetFlowinstanceByBusyId(busyid)
	// // 针对退回的单据重新生成流程实例
	// if ts.Status == 3 {
	// 	models.ReApply(user.Id, busyid, ts)
	// 	flow, _ := models.GetFlowByName("采购单")
	// 	ts, _ = models.InitFSM(user, flow.Id, "Assetsbuy", busyid)
	// }
	// beego.Debug("ts err: ", ts)
	// fsm := models.GetFSM(ts)
	// // beego.Debug("fsm err: ", fsm)
	// ev, _ := models.GetEventByName("上报")
	// err = fsm.Trigger(ts.Currentstate, ev.Id, ts)
	// if err != nil {
	// 	beego.Error("trigger err: ", err)
	// 	c.RetError(ErrPermission)
	// }

	c.RetSuccess(sdata)

}

// GetMyOrder ...
// @Title GetMyOrder
// @Description 获取用户销售单
// @Param	body		body 	models.Order	true		"body for Assetsbuy content"
// @Success 201 {int} models.Order
// @Failure 403 body is empty
// @router /GetMyOrder [get]
func (c *OrderController) GetMyOrder() {
	user := c.User
	if orders, err := models.GetOrderByUserAndStatus(user.Id,1); err == nil {
		c.RetSuccess(orders)
	} else {
		beego.Debug(err)
		c.RetError( ErrDatabase)
	}
}
